using Microsoft.AspNetCore.Mvc;
using Common.dto;
using Common.Shared.resp;
using AutoMapper;
using WebApi.model;
using WebApi.service;

namespace WebApi.Controllers
{
    [ApiController]
    [Route("/api/[controller]/[action]")]
    public class LoginController : ControllerBase
    {
        private readonly IMapper mapper;
        private readonly IUserService userService;

        public LoginController(IMapper mapper,IUserService userService)
        {
            this.mapper = mapper;
            this.userService = userService;
        }

        [HttpPost]
        public Resp<object> Register([FromBody] UserDto userDto)
        {
            User user = ToUserModel(userDto);

            userService.Register(user);

            return Resp<object>.Success();
        }

        private User ToUserModel(UserDto userDto)
        {
            return mapper.Map<User>(userDto);
        }

        [HttpPost]
        public Resp<object> Login([FromBody] UserDto userDto)
        {
            string? token = userService.Login(ToUserModel(userDto));

            if (token is null)
            {
                return Resp<object>.Fail("用户不存在");
            }
            
            return Resp<object>.Success(token);
        }
    }
}
